package mines.fila3.letstalk.activities;

import java.io.IOException;
import java.io.InputStream;

import mines.fila3.letstalk.R;
import mines.fila3.letstalk.params.LetsTalkConst;
import mines.fila3.letstalk.tools.InputStreamConverter;
import mines.fila3.letstalk.tools.LetsTalkNetwork;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.os.AsyncTask;
import android.os.AsyncTask.Status;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Toast;

public class LoginActivity extends Activity {

	private EditText etUsername;
	private EditText etPassword;
	private Button bReset;
	private Button bValidate;
	private ProgressBar progressbar;
	private LoginTask logintask;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_login);
		bindComponents();
		addListenners();

		// TODO A supprimer lors du rendu
		etUsername.setText("letstalk");
		etPassword.setText("letstalk");
	}

	private void bindComponents() {
		etUsername = (EditText) this.findViewById(R.id.et_username);
		etPassword = (EditText) this.findViewById(R.id.et_password);
		bReset = (Button) this.findViewById(R.id.btn_cancel);
		bValidate = (Button) this.findViewById(R.id.btn_validate);
		progressbar = (ProgressBar) findViewById(R.id.progressbar);

		SharedPreferences prefs = getSharedPreferences(LetsTalkConst.USER_CREDENTIALS, MODE_PRIVATE);
		String username = prefs.getString(LetsTalkConst.KEY_USERNAME, LetsTalkConst.EMPTY_STRING);
		String password = prefs.getString(LetsTalkConst.KEY_PASSWORD, LetsTalkConst.EMPTY_STRING);

		if (!username.isEmpty() && !password.isEmpty()) {
			etUsername.setText(username);
			etPassword.setText(password);
		}
	}

	private void addListenners() {
		bReset.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				etUsername.setText(LetsTalkConst.EMPTY_STRING);
				etPassword.setText(LetsTalkConst.EMPTY_STRING);
				Toast.makeText(getApplicationContext(), getString(R.string.msg_reset), Toast.LENGTH_SHORT)
						.show();
			}
		});

		bValidate.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {

				if (LetsTalkNetwork
						.isConnected((ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE))) {

					if (logintask == null || logintask.getStatus() == Status.FINISHED) {
						logintask = new LoginTask();
					}
					if (logintask.getStatus() == Status.PENDING) {
						logintask.execute();
					}
				} else {
					Toast.makeText(getApplicationContext(), R.string.msg_no_connection, Toast.LENGTH_SHORT)
							.show();
				}
			}
		});
	}

	private class LoginTask extends AsyncTask<String, Void, Boolean> {

		@Override
		protected void onPreExecute() {
			LoginActivity.this.progressbar.setVisibility(View.VISIBLE);
		}

		@Override
		protected Boolean doInBackground(String... params) {

			// recuperer username & password
			String username = etUsername.getText().toString().trim();
			String password = etPassword.getText().toString().trim();

			if (username == null || username.trim().isEmpty() || password == null || password.trim().isEmpty()) {
				return false;
			}

			try {
				DefaultHttpClient client = new DefaultHttpClient();

				HttpGet request = new HttpGet(LetsTalkConst.getAdressHTTP(LetsTalkConst.QUERY_CONNECT,
						username, password));
				HttpResponse response = client.execute(request);

				InputStream content = response.getEntity().getContent();

				return InputStreamConverter.convertToBoolean(content);

			} catch (ClientProtocolException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}

			return false;
		}

		@Override
		protected void onPostExecute(Boolean result) {
			// execute dans l'UIThread
			// rendre la roue invisble
			LoginActivity.this.progressbar.setVisibility(View.INVISIBLE);

			if (result) {
				Toast.makeText(getApplicationContext(), getString(R.string.msg_login_ok), Toast.LENGTH_SHORT)
						.show();

				SharedPreferences prefs = getSharedPreferences(LetsTalkConst.USER_CREDENTIALS, MODE_PRIVATE);
				SharedPreferences.Editor editor = prefs.edit();
				editor.putString(LetsTalkConst.KEY_USERNAME, etUsername.getText().toString());
				editor.putString(LetsTalkConst.KEY_PASSWORD, etPassword.getText().toString());
				editor.commit();

				// lancement d'une nouvelle activite
				Intent intent = new Intent(LoginActivity.this, ListMessagesActivity.class);
				startActivity(intent);
				LoginActivity.this.finish();
			} else {
				SharedPreferences prefs = getSharedPreferences(LetsTalkConst.USER_CREDENTIALS, MODE_PRIVATE);
				String username = prefs.getString(LetsTalkConst.KEY_USERNAME, LetsTalkConst.EMPTY_STRING);
				String password = prefs.getString(LetsTalkConst.KEY_PASSWORD, LetsTalkConst.EMPTY_STRING);

				if (username.equals(etUsername.getText().toString())
						&& password.equals(etPassword.getText().toString())) {
					prefs.edit().remove(LetsTalkConst.KEY_USERNAME);
					prefs.edit().remove(LetsTalkConst.KEY_PASSWORD);
					prefs.edit().commit();
				}
				Toast.makeText(getApplicationContext(), getString(R.string.msg_bad_login), Toast.LENGTH_LONG)
						.show();
			}

		}
	}

	@Override
	protected void onRestoreInstanceState(Bundle savedInstanceState) {
		Log.i("TAG", "onrestore");
		super.onRestoreInstanceState(savedInstanceState);
		String oldUsername = savedInstanceState.getString(LetsTalkConst.KEY_USERNAME);
		String username = getSharedPreferences(LetsTalkConst.USER_CREDENTIALS, MODE_PRIVATE).getString(
				LetsTalkConst.KEY_USERNAME, LetsTalkConst.EMPTY_STRING);

		savedInstanceState.getInt("KEY_INT");

		Log.i("TAG", oldUsername);
		Log.i("TAG", username);
	}

}
